##  Downloadr. An application that allows you to download entire sets of Flickr Photos.
##  Copyright (C) 2008  Joshua Henderson
##  
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##  
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##  
##  You should have received a copy of the GNU General Public License
##  along with this program.  If not, see <http://www.gnu.org/licenses/>.

##  Created by Joshua Henderson <joshhendo@gmail.com>
##			        <http://joshhendo.com>
##
##  Based on work by James Clarke <james@jamesclarke.info>
##  flickr.py: http://code.google.com/p/flickrpy

# Importing Custom Python Modules needed
import flickr

# Importing standard Python Modules needed
import sys
import os
import hashlib
import urllib2
import webbrowser
import time
import threading

def getURL(photo, size, equal=False):
    """Retrieves a url for the photo.  (flickr.photos.getSizes)
        
    photo - the photo
    size - what size 'Thumbnail, Small, Medium, Large, Original'
    equal - should width == height?
    """
    method = 'flickr.photos.getSizes'
    #token = getToken()
    api_signature = hashlib.md5(flickr.API_SECRET + 'api_key' + flickr.API_KEY + 'method' + method + 'photo_id' + photo).hexdigest()
    
    data = flickr._doget(method, photo_id=photo, api_sig=api_signature)
    for psize in data.rsp.sizes.size:
        if psize.label == size:
            print "got to here!"
            if equal and psize.width == psize.height:
                    return psize.source
            elif not equal:
                return psize.source
    raise flickr.FlickrError, "No URL found"

def getPhotos(setID):
    """Returns list of Photos."""
    global downloadNumber
    downloadNumber = 0
    method = 'flickr.photosets.getPhotos'
    #token = getToken()
    api_signature = hashlib.md5(flickr.API_SECRET + 'api_key' + flickr.API_KEY + 'method' + method + 'photoset_id' + setID).hexdigest()
    
    data = flickr._doget(method, photoset_id=setID, api_sig=api_signature)
    photos = data.rsp.photoset.photo
    p = []
    downloadNumber = 0
    for photo in photos:
        p.append(photo.id)
        downloadNumber = downloadNumber + 1
        print "downloadNUMBER: " + str(downloadNumber)
    return p

def processSet(setID, size, directory):
    #directory = os.path.join("/" + "tmp", "downloadr" + "/" + setID)
    
    global downloadProgress
    downloadProgress = 5
    
    if os.path.exists(directory):
        os.popen("rm -r " + directory)
        os.mkdir(directory,0777)
    if not os.path.exists(directory):
        os.mkdir(directory,0777)
    
    myPhotos = getPhotos(setID)
    downloadProgress = 0
    
    for each in myPhotos:
        myUrl = getURL(each, size, False)
        result = urllib2.urlopen(myUrl).read() #please check syntax
        open(os.path.join(directory,each),"w").write(result)
        downloadProgress = downloadProgress + 1

def CheckTokenFile():
    f = os.path.join(os.path.dirname(__file__),"token.txt")
    try:
        file = open(f)
    except IOError:
        exists = 0
    else:
        exists = 1
    return exists

def RemoveToken():
    f = os.path.join(os.path.dirname(__file__),"token.txt")
    os.remove(f)
    return 1

frob = "no frob yet :("


def AuthBrowser(self):
    global myAuth
    myAuth = flickr.Auth()
    permission = "read"
    global frob
    frob = myAuth.getFrob()
    
    link = myAuth.loginLink(permission,frob)
    webbrowser.open(link)

def AuthCompleted(self):
    token = myAuth.getToken(frob)
    f = os.path.join(os.path.dirname(__file__),"token.txt")
    storage = file(f,'w')
    storage.write(token)
    storage.close()
    
def AuthTest(self):
    user = flickr.test_login()
    return user

def DeleteToken(self):
    f = os.path.join(os.path.dirname(__file__),"token.txt")
    try:
        os.remove(f)
    except:
        return 0
    return 1

def getList(idToDownload):
    print "hi"
    global listOfImages
    listOfImages = flickr.downloadrGetPhotos(idToDownload)
    return listOfImages

def getPreview(photoIdToPreview):
    print "getting preview"
    print photoIdToPreview
    myUrl = getURL(photoIdToPreview, "Small")
    result = urllib2.urlopen(myUrl).read() #please check syntax
    #open(os.path.join(os.path.dirname(__file__),"image.jpg"),"w").write(result)
    #saveLocation = os.path.join("tmp",".downloadr","image.jpg")
    saveLocation = os.path.join(os.path.dirname(__file__),"image.jpg")
    open(saveLocation,"w").write(result)
    return saveLocation

#def getToken():
#	f = file('/home/josh/.downloadr/information.txt','r')
#	token = f.read()
#	f.close()
#	return token

#token = getToken()
#method = 'flickr.photos.getSizes'
#print flickr.API_SECRET + 'api_key' + flickr.API_KEY + 'auth_token' + token + 'method' + method
#print hashlib.md5(flickr.API_SECRET + 'api_key' + flickr.API_KEY + 'auth_token' + token + 'method' + method).hexdigest()

#processSet(sys.argv[1], "Original")
